<template>
  <Form
    :schema="status==1?schemas:schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="register"
  >
  
    <template #title> 
      <div class="loginTitleBox"> 
        <span @click="status=1" :class="status==1?'on':''">账号登录</span>
        <span @click="status=2" :class="status==2?'on':''">坐席登录</span>
      </div>
      
      <!-- <h2 class="text-2xl font-bold text-center w-[100%]">{{ t('login.login') }}</h2> -->
    </template>
    <template #captcha="form">
      <div class="flex w-[100%]">
        <ElInput v-model="form['captcha']" :placeholder="t('login.codePlaceholder')" />
        <img
          v-if="requestCodeSuccess"
          style="margin-top: 2px"
          :src="randCodeImage"
          @click="handleChangeCheckCode"
        />
        <img
          v-else
          style="margin-top: 2px"
          src="@/assets/imgs/checkcode.png"
          @click="handleChangeCheckCode"
        />
      </div>
    </template>
    <!-- <template #tool>
      <div class="flex justify-between items-center w-[100%]">
        <ElCheckbox v-model="remember" :label="t('login.remember')" size="small" />
        <ElLink type="primary" :underline="false">{{ t('login.forgetPassword') }}</ElLink>
      </div>
    </template> -->

    <template #login>
      <div class="w-[100%]">
        <ElButton :loading="loading" type="primary" class="w-[100%]" @click="signIn">
          {{ t('login.login') }}
        </ElButton>
      </div>
      <!-- <div class="w-[100%] mt-15px">
        <ElButton class="w-[100%]" @click="toRegister">
          {{ t('login.register') }}
        </ElButton>
      </div> -->
    </template>
  </Form>
</template>

<script setup lang="ts">
import { reactive, ref, unref, watch, onMounted, onUnmounted } from 'vue'
import { Form } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
// import { loginApiI, loginCodeApi, getUserInfo, getQueryByUser } from '@/api/login'
import { loginApiI, loginCodeApi, getQueryByUser } from '@/api/login'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { FormSchema } from '@/types/form'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import actions from "@/hooks/web/useActions";
import { ElLoading } from 'element-plus'

const { required } = useValidator()

// const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { wsCache } = useCache()

const { t } = useI18n()

let loadingInstance:any = null;

const rules = {
  username: [required()],
  password: [required()],
  captcha: [required()]
}

let status = ref(1)

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder')
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: t('login.passwordPlaceholder')
    }
  },
  {
    field: 'captcha',
    label: t('login.captcha'),
    colProps: {
      span: 24
    }
  },
  {
    field: 'seatNumber',
    label: t('login.seatNumber'),
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.seatNumberPlaceholder')
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    }
  }
])


const schemas = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder')
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: t('login.passwordPlaceholder')
    }
  },
  // {
  //   field: 'captcha',
  //   label: t('login.captcha'),
  //   colProps: {
  //     span: 24
  //   }
  // }, 
  {
    field: 'login',
    colProps: {
      span: 24
    }
  }
])

onMounted(() => {
  handleChangeCheckCode()
  // 监听enter事件（调用登录）
  // document.onkeydown = (e: any) => {
  //   e = window.event || e
  //   if (e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
  //     if (loading.value) return
  //     signIn()
  //   }
  // }
})
onUnmounted(() => {
  document.onkeydown = null
})
// const iconSize = 30

const currdatetime = ref() // 时间戳
const requestCodeSuccess = ref(true) // 验证码判断
let randCodeImage: any = ref('') // 验证码地址
// 验证码请求
const handleChangeCheckCode = async () => {
  currdatetime.value = new Date().getTime()
  const res = await loginCodeApi(currdatetime.value)
  if (res.success) {
    randCodeImage.value = res.result
    requestCodeSuccess.value = true
  } else {
    requestCodeSuccess.value = false
  }
}

// const remember = ref(false)

const { register, elFormRef, methods } = useForm()

const loading = ref(false)

// const iconColor = '#999'

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

const routerGo = (href = '/', title = '', stateObj = {}) => {
  setTimeout(() => {
    loadingInstance.close()
  }, 100)
  window.history.pushState(stateObj, title, href)
}

// 登录
const signIn = async () => {
  const formRef = unref(elFormRef)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const { getFormData } = methods
      const form = await getFormData<UserType>()
      Object.assign(form, { checkKey: currdatetime.value }) // 添加事件戳
      try {

        if(status.value == 2){
          if(!form.seatNumber){
            ElMessage.error("请输入座位号！");
            return;
          }
        }
        
        const res1 = await loginApiI(form)
        if (res1.success) {
          appStore.setToken(res1.result.token) //session里存token
          wsCache.set('dictionary',res1.result.sysAllDictItems) //session里存字典
          wsCache.set('roleInfo',res1.result.roleInfo) //session里存权限

          actions.setGlobalState({
            userInfo: res1.result.userInfo,
            token: res1.result.token,
            roleInfo: res1.result.roleInfo,
            seatNumber: form.seatNumber
          });

          // 获取用户信息
          // const res = await getUserInfo()
          const { result } = await getQueryByUser({ username: res1.result.userInfo.username }) 
          appStore.setDynamicRouter(true) //session里存是否是动态路由
          wsCache.set('roleRouters', result || []) //session里存动态路由
          wsCache.set(appStore.getUserInfo, res1.result.userInfo) //session里存用户信息
          wsCache.set('user', res1.result.userInfo)

          if(status.value == 2){
            wsCache.set('seatNumber',form.seatNumber);
          }

          await permissionStore.generateRoutes('admin', result || []).catch(() => {})
          permissionStore.getAddRouters.forEach((route) => {
            addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
          })
          permissionStore.setIsAddRouters(true)

          if (qiankunWindow.__POWERED_BY_QIANKUN__) {
            actions.setGlobalState({ token: res1.result.token });
            loadingInstance = ElLoading.service({ fullscreen: true })
            routerGo('/', '石家庄交管局民意监管平台',{})
          } else {
            push({ path: redirect.value || permissionStore.addRouters[0].path })
          }
        } else {
          ElMessage.error(res1.message)
          handleChangeCheckCode()
          return
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 去注册页面
// const toRegister = () => {
//   emit('to-register')
// }
</script>

<style lang="less" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.loginTitleBox{
  width: 100%;
  span{
    font-size: 18px;
    display: inline-block;
    width: 50%;
    text-align: center;
    cursor: pointer;
  }
  .on{
    border-bottom: 2px #1890ff solid;
  }
}
</style>
